package com.bawei.module_launcher.splash

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_launcher.splash.model.SplashService
import com.bw.launcher.splash.entity.LockEntity
import com.bw.launcher.splash.entity.LockErroEntity
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : 
 * @Time : On 2023/7/24 16:29
 * @Description : SplashViewModel
 */
class SplashViewModel:BaseViewModel<SplashIntent>() {
    private val service:SplashService by lazy{SplashService()}
    private val _states = MutableStateFlow<SplashState>(SplashState.Init)//MutableStateFlow可变
    val states: StateFlow<SplashState>
        get() = _states

    //处理意图
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is SplashIntent.SplashWhiteIntent -> requestWhite()
                }
            }
        }

    }
    //请求白名单：先请求是否锁屏->
    private fun requestWhite() {
        viewModelScope.launch {
            flow {
                val requestLock = service.requestLock()//请求锁屏
                if(requestLock.statusCode == 200){
                    _states.value = SplashState.SplashLockState //锁屏
                }else{
                    _states.value = SplashState.SplashUnLockState //不锁屏
                    val requestWhite = service.requestWhite()//请求白名单
                    emit(requestWhite)//结果提交
                }
            }.collect{
                val datas = it.datas
                _states.value = SplashState.SplashWhiteState(datas)//白名单状态
            }
        }

    }
}